package com.aysafety.iotdataplatformserver.listener;

import com.alibaba.fastjson.JSON;
import com.aysafety.core.DBDriver.hbase.HBaseDriver;
import com.aysafety.core.common.DateUtils;
import com.aysafety.core.model.GeosoundModel;
import com.aysafety.iotdataplatformserver.dao.GeosoundDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 地音
@Component public class GeosoundListener {

    private final String type = "Geosound";

    private final String tableName = "GeosoundRealTime";

    private final String calTableName = "CalGeoSound";

    private final String[] calStructure = new String[] {"Energy", "pulse"};

    private final String calDailyTableName = "CalDailyGeoSound";

    private final String[] calDailyStructure = new String[] {"dailyValue"};

    private final String calWarningTableName = "CalWarningGeoSound";

    private final String[] calWarningStructure = new String[] {"warning"};


    private final String[] structure = new String[] {"Geosound"};

    @Autowired KsTreeDataListener ksTreeDataListener;

    @Autowired GeosoundDao geosoundDao;

    private Logger logger = LoggerFactory.getLogger(ErrorListener.class);

    public boolean createTable() throws IOException {
        return HBaseDriver.createTable(this.tableName, this.structure);
    }

    public boolean createCalTable() throws IOException {
        return HBaseDriver.createTable(this.calTableName, this.calStructure);
    }

    public boolean createCalDailyTable() throws IOException {
        return HBaseDriver.createTable(this.calDailyTableName, this.calDailyStructure);
    }

    public boolean createCalWarningTable() throws IOException {
        return HBaseDriver.createTable(this.calWarningTableName, this.calWarningStructure);
    }

    public void start(Map<String, Object> result) {
        logger.info("GeosoundListener.start,result=" + result);
        try {
            String clientId = result.get("clientId").toString();
            if (!result.get("dataType").toString().equals("histroy")) {
                List<Map<String, Object>> listDatas = JSON.parseObject(result.get("data").toString(), List.class);
                for (Map<String, Object> listData : listDatas) {
                    GeosoundModel geosoundData = this.transformData(listData);
                    this.save(geosoundData, clientId);
                }
            } else {
                List<Map<String, Object>> listDatas = JSON.parseObject(result.get("data").toString(), List.class);
                for (Map<String, Object> listData : listDatas) {
                    GeosoundModel geosoundData = this.transformData(listData);
                    this.save(geosoundData, clientId);
                }
            }
        } catch (IOException e) {
            logger.info("GeosoundListener:", e);
        }
    }

    public boolean save(GeosoundModel geosoundData, String clientId) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("entId", "\'" + geosoundData.getEntId() + "\'");

        String deviceId = geosoundData.getDeviceId();
        String workingFace = geosoundData.getWorkingFace();
        List<Map<String, Object>> filters = geosoundDao.queryFilter(map);
        boolean flag = true;
        for (int i = 0; i < filters.size(); i++) {
            Map<String, Object> filterMap = filters.get(i);
            if (filterMap.get("DEVICEID").toString().trim().equals(deviceId.trim())) {
                flag = false;
                break;
            }
        }
        if (flag) {
            String timestamp = String.valueOf(geosoundData.getDatetime().getTime());
            map.put("tableId", geosoundData.getEntId() + "." + "GeosoundRealTime");
            map.put("pk", "\'" + timestamp + ".:." + geosoundData.getDeviceId() + "\'");
            map.put("clientId", "\'" + clientId + "\'");
            map.put("deviceId", "\'" + deviceId + "\'");
            map.put("pos", "\'" + geosoundData.getPos() + "\'");
            map.put("workingFace", "\'" + workingFace + "\'");
            map.put("datetime", geosoundData.getDatetime().getTime());
            map.put("emergoa", geosoundData.getEmergoa());
            map.put("poklad", geosoundData.getPoklad());
            map.put("probePos", "\'" + geosoundData.getProbePos() + "\'");
            geosoundDao.insertRealGeosound(map);
            ksTreeDataListener.generateTreeData(geosoundData.getEntId(), this.type, geosoundData.getWorkingFace(),
                geosoundData.getDeviceId(), geosoundData.getDatetime(), geosoundData.getPos());
        }
        return true;
    }

    public GeosoundModel transformData(Map<String, Object> result) {
        GeosoundModel geosoundData = new GeosoundModel();
        geosoundData.setEntId(result.get("entId").toString());
        geosoundData.setDeviceId(result.get("deviceId").toString());
        if (null != result.get("emergoa")) {
            geosoundData.setEmergoa(Double.valueOf(result.get("emergoa").toString()));
        } else {
            geosoundData.setEmergoa(-1.0);
        }
        if (null != result.get("poklad")) {
            geosoundData.setPoklad(Double.valueOf(result.get("poklad").toString()));
        } else {
            geosoundData.setPoklad(-1.0);
        }
        geosoundData.setDatetime(DateUtils.fomatDateTime(Long.valueOf(result.get("datetime").toString())));
        if (null != result.get("workingFace")) {
            geosoundData.setWorkingFace(result.get("workingFace").toString());
        } else {
            geosoundData.setWorkingFace("无数据");
        }
        if (null != result.get("pos")) {
            geosoundData.setPos(result.get("pos").toString());
        } else {
            geosoundData.setPos("无数据");
        }
        if (null != result.get("probePos")) {
            geosoundData.setProbePos(result.get("probePos").toString());
        } else {
            geosoundData.setProbePos("无数据");
        }
        return geosoundData;
    }
}
